/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl;

import com.je.bpm.engine.history.*;
import com.je.bpm.engine.impl.interceptor.Command;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.interceptor.CommandExecutor;
import com.je.bpm.engine.impl.persistence.entity.HistoricProcessInstanceEntity;
import com.je.bpm.engine.impl.persistence.entity.HistoricVariableInstanceEntity;
import com.je.bpm.engine.impl.variable.CacheableVariable;

import java.util.List;


public class ProcessInstanceHistoryLogQueryImpl implements ProcessInstanceHistoryLogQuery, Command<ProcessInstanceHistoryLog> {

    protected CommandExecutor commandExecutor;

    protected String processInstanceId;
    protected boolean includeTasks;
    protected boolean includeActivities;
    protected boolean includeVariables;
    protected boolean includeComments;
    protected boolean includeVariableUpdates;
    protected boolean includeFormProperties;

    public ProcessInstanceHistoryLogQueryImpl(CommandExecutor commandExecutor, String processInstanceId) {
        this.commandExecutor = commandExecutor;
        this.processInstanceId = processInstanceId;
    }

    @Override
    public ProcessInstanceHistoryLogQuery includeTasks() {
        this.includeTasks = true;
        return this;
    }

    @Override
    public ProcessInstanceHistoryLogQuery includeComments() {
        this.includeComments = true;
        return this;
    }

    @Override
    public ProcessInstanceHistoryLogQuery includeActivities() {
        this.includeActivities = true;
        return this;
    }

    @Override
    public ProcessInstanceHistoryLogQuery includeVariables() {
        this.includeVariables = true;
        return this;
    }

    @Override
    public ProcessInstanceHistoryLogQuery includeVariableUpdates() {
        this.includeVariableUpdates = true;
        return this;
    }

    @Override
    public ProcessInstanceHistoryLogQuery includeFormProperties() {
        this.includeFormProperties = true;
        return this;
    }

    @Override
    public ProcessInstanceHistoryLog singleResult() {
        return commandExecutor.execute(this);
    }

    @Override
    public ProcessInstanceHistoryLog execute(CommandContext commandContext) {

        // Fetch historic process instance
        HistoricProcessInstanceEntity historicProcessInstance = commandContext.getHistoricProcessInstanceEntityManager().findById(processInstanceId);

        if (historicProcessInstance == null) {
            return null;
        }

        // Create a log using this historic process instance
        ProcessInstanceHistoryLogImpl processInstanceHistoryLog = new ProcessInstanceHistoryLogImpl(historicProcessInstance);

        // Add events, based on query settings

        // Tasks
        if (includeTasks) {
            List<? extends HistoricData> tasks = commandContext.getHistoricTaskInstanceEntityManager().findHistoricTaskInstancesByQueryCriteria(
                    new HistoricTaskInstanceQueryImpl(commandExecutor).processInstanceId(processInstanceId));
            processInstanceHistoryLog.addHistoricData(tasks);
        }

        // Activities
        if (includeActivities) {
            List<HistoricActivityInstance> activities = commandContext.getHistoricActivityInstanceEntityManager().findHistoricActivityInstancesByQueryCriteria(
                    new HistoricActivityInstanceQueryImpl(commandExecutor).processInstanceId(processInstanceId), null);
            processInstanceHistoryLog.addHistoricData(activities);
        }

        // Variables
        if (includeVariables) {
            List<HistoricVariableInstance> variables = commandContext.getHistoricVariableInstanceEntityManager().findHistoricVariableInstancesByQueryCriteria(
                    new HistoricVariableInstanceQueryImpl(commandExecutor).processInstanceId(processInstanceId), null);

            // Make sure all variables values are fetched (similar to the HistoricVariableInstance query)
            for (HistoricVariableInstance historicVariableInstance : variables) {
                historicVariableInstance.getValue();
                //todo 此处去除jpa处理
            }

            processInstanceHistoryLog.addHistoricData(variables);
        }

        // Comment
        if (includeComments) {
            List<? extends HistoricData> comments = commandContext.getCommentEntityManager().findCommentsByProcessInstanceId(processInstanceId);
            processInstanceHistoryLog.addHistoricData(comments);
        }

        // Details: variables
        if (includeVariableUpdates) {
            List<? extends HistoricData> variableUpdates = commandContext.getHistoricDetailEntityManager().findHistoricDetailsByQueryCriteria(
                    new HistoricDetailQueryImpl(commandExecutor).variableUpdates(), null);

            // Make sure all variables values are fetched (similar to the HistoricVariableInstance query)
            for (HistoricData historicData : variableUpdates) {
                HistoricVariableUpdate variableUpdate = (HistoricVariableUpdate) historicData;
                variableUpdate.getValue();
            }

            processInstanceHistoryLog.addHistoricData(variableUpdates);
        }

        // Details: form properties
        if (includeFormProperties) {
            List<? extends HistoricData> formProperties = commandContext.getHistoricDetailEntityManager().findHistoricDetailsByQueryCriteria(
                    new HistoricDetailQueryImpl(commandExecutor).formProperties(), null);
            processInstanceHistoryLog.addHistoricData(formProperties);
        }

        // All events collected. Sort them by date.
        processInstanceHistoryLog.orderHistoricData();

        return processInstanceHistoryLog;
    }

}
